import LogFactory from "../log/LogFactory.js";
import RequestHandler from "../util/RequestHadler.js";
import DashboardResolver from "./DashboardResolver.js";
import LastReport from "./LastReport.js";
const log = LogFactory.getLogger("GameDelegate");
/**
 * 游戏委托处理类
 */
export default class GameDelegate {

    #lastReport = new LastReport();
    #dashboard = new DashboardResolver();
    #comp = null;
    #gameData = null;

    /**
     * 初始化游戏数据
     */
    async init(comp) {
        // log.debug("游戏委托处理初始化");
        this.#comp = comp;
        await this.loadFragment();
        await this.loadGameData();
        setTimeout(()=> this.#parseDataCallFun(), 50);
    }

    #parseDataCallFun(){
        const { lastScoring, total, userTotal, userLandlord } = this.#gameData;
        this.#lastReport.renderData(lastScoring);
        this.#dashboard.renderData(total,userLandlord,userTotal);
    }

    /**
     * 刷新页面
     */
    async refreshPage() {
        log.debug("刷新页面");
        await this.loadGameData();
        this.#parseDataCallFun();
    }


    /**
     * 加载游戏数据
     */
    async loadGameData() {
        this.#gameData = await RequestHandler.get("/scoring/game-detail");
        //    log.debug("加载游戏数据", this.#gameData);
    }

    /**
     * 加载代码片段
     */
    async loadFragment() {
        // log.debug("开始加载代码片段");
        const fragments = [
            fetch('../fragment/dashboard.html'),
            fetch('../fragment/last-report.html'),
            fetch('../fragment/score-form.html')
        ];
        // log.debug("开始加载代码片段", fps);
        const results = await Promise.all(fragments.map(async (fp) => {
            const response = await fp;
            // log.debug("加载代码片段", response);
            if (response.ok) {
                return response.text();
            }
            log.warn("加载代码片段错误: ", response);
            return "";
        }));
        document.getElementById('dashboard').innerHTML = results[0];
        document.getElementById('lastReport').innerHTML = results[1];
        document.getElementById('scoreForm').innerHTML = results[2];
        setTimeout(() => {
            // log.debug("初始化组件");
            this.#dashboard.init();
            this.#lastReport.init();
            this.#comp.init();
        }, 50);
    }

}